<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>经典贪吃蛇游戏</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            background: linear-gradient(135deg, #1a1a2e, #16213e);
            color: #f1f1f1;
            padding: 20px;
        }
        
        .container {
            max-width: 500px;
            width: 100%;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }
        
        header {
            background: linear-gradient(to right, #e74c3c, #e67e22);
            padding: 20px;
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        h1 {
            font-size: 2.8rem;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
            letter-spacing: 2px;
        }
        
        .game-info {
            display: flex;
            justify-content: space-between;
            width: 100%;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 10px;
            padding: 10px 20px;
            margin-top: 15px;
        }
        
        .score-container, .high-score-container {
            text-align: center;
        }
        
        .label {
            font-size: 0.9rem;
            opacity: 0.8;
            margin-bottom: 5px;
        }
        
        .score, .high-score {
            font-size: 1.8rem;
            font-weight: bold;
        }
        
        .game-area {
            background: #0f3460;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 25px;
            min-height: 400px;
        }
        
        #game-canvas {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 5px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
        }
        
        .controls {
            padding: 20px;
            background: #16213e;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            justify-content: center;
        }
        
        button {
            padding: 12px 25px;
            font-size: 1.1rem;
            background: linear-gradient(to right, #3498db, #2ecc71);
            color: white;
            border: none;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            min-width: 120px;
            font-weight: bold;
        }
        
        button:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
        }
        
        button:active {
            transform: translateY(1px);
        }
        
        #reset-btn {
            background: linear-gradient(to right, #e74c3c, #e67e22);
        }
        
        .instructions {
            margin-top: 30px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 15px;
            padding: 20px;
            max-width: 500px;
            width: 100%;
        }
        
        .instructions h2 {
            font-size: 1.5rem;
            color: #3498db;
            margin-bottom: 15px;
            text-align: center;
        }
        
        .instructions ul {
            list-style-type: none;
            padding: 0 20px;
        }
        
        .instructions li {
            margin: 10px 0;
            padding-left: 30px;
            position: relative;
        }
        
        .instructions li:before {
            content: "→";
            position: absolute;
            left: 0;
            color: #2ecc71;
            font-weight: bold;
        }
        
        .mobile-controls {
            display: none;
            margin-top: 20px;
            grid-template-columns: 1fr 1fr 1fr;
            grid-template-rows: 1fr 1fr;
            gap: 10px;
            width: 100%;
            max-width: 300px;
        }
        
        .mobile-controls button {
            min-width: auto;
            padding: 15px;
            font-size: 1.5rem;
        }
        
        .mobile-controls .up {
            grid-column: 2;
            grid-row: 1;
        }
        
        .mobile-controls .left {
            grid-column: 1;
            grid-row: 2;
        }
        
        .mobile-controls .down {
            grid-column: 2;
            grid-row: 2;
        }
        
        .mobile-controls .right {
            grid-column: 3;
            grid-row: 2;
        }
        
        @media (max-width: 500px) {
            .mobile-controls {
                display: grid;
            }
        }
        
        .snake-segment {
            position: relative;
        }
        
        .snake-segment::before {
            content: "";
            position: absolute;
            width: 30%;
            height: 30%;
            background: rgba(255, 255, 255, 0.6);
            border-radius: 50%;
            top: 15%;
            left: 15%;
        }
        
        .game-over {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.85);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 10;
            display: none;
        }
        
        .game-over-content {
            background: linear-gradient(135deg, #16213e, #0f3460);
            padding: 40px;
            border-radius: 20px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.7);
            max-width: 90%;
            width: 500px;
        }
        
        .game-over h2 {
            font-size: 3rem;
            color: #e74c3c;
            margin-bottom: 20px;
        }
        
        .game-over p {
            font-size: 1.8rem;
            margin: 20px 0;
        }
        
        .final-score {
            font-weight: bold;
            color: #f39c12;
            font-size: 2.5rem;
        }
        
        .highlight {
            color: #2ecc71;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>贪吃蛇大冒险</h1>
            <div class="game-info">
                <div class="score-container">
                    <div class="label">当前分数</div>
                    <div class="score">0</div>
                </div>
                <div class="high-score-container">
                    <div class="label">最高分数</div>
                    <div class="high-score">0</div>
                </div>
            </div>
        </header>
        
        <div class="game-area">
            <canvas id="game-canvas" width="400" height="400"></canvas>
        </div>
        
        <div class="controls">
            <button id="start-btn">开始游戏</button>
            <button id="pause-btn">暂停游戏</button>
            <button id="reset-btn">重新开始</button>
        </div>
    </div>
    
    <div class="mobile-controls">
        <button class="up">↑</button>
        <button class="left">←</button>
        <button class="down">↓</button>
        <button class="right">→</button>
    </div>
    
    <div class="instructions">
        <h2>游戏指南</h2>
        <ul>
            <li>使用<span class="highlight">方向键</span>（或屏幕上的按钮）控制蛇的移动方向</li>
            <li>吃到<span class="highlight">绿色食物</span>可以增加蛇的长度并获取10分</li>
            <li>撞到墙壁或自己的身体会导致<span class="highlight">游戏结束</span></li>
            <li>每吃到5个食物，蛇的移动速度会<span class="highlight">稍微加快</span></li>
            <li>挑战自己，努力<span class="highlight">创造新纪录</span>吧！</li>
        </ul>
    </div>
    
    <div class="game-over">
        <div class="game-over-content">
            <h2>游戏结束</h2>
            <p>最终分数: <span class="final-score">0</span></p>
            <button id="play-again-btn">再来一局</button>
        </div>
    </div>

    <script>
        // 游戏核心变量
        const canvas = document.getElementById('game-canvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.querySelector('.score');
        const highScoreElement = document.querySelector('.high-score');
        const finalScoreElement = document.querySelector('.final-score');
        
        // 尺寸配置
        const gridSize = 20;
        const tileCount = canvas.width / gridSize;
        
        // 蛇初始状态
        let snake = [];
        let snakeLength = 3;
        let snakeX = 10;
        let snakeY = 10;
        
        // 食物位置
        let foodX = 15;
        let foodY = 15;
        
        // 游戏状态
        let dx = 0; // x方向移动
        let dy = 0; // y方向移动
        let score = 0;
        let highScore = localStorage.getItem('snakeHighScore') || 0;
        let gameSpeed = 120;
        let gameInterval;
        let isPaused = true;
        let gameOver = false;
        
        // 初始化最高分数显示
        highScoreElement.textContent = highScore;
        
        // 绘制游戏元素
        function drawGame() {
            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制网格线
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
            ctx.lineWidth = 0.5;
            for (let i = 0; i < tileCount; i++) {
                ctx.beginPath();
                ctx.moveTo(i * gridSize, 0);
                ctx.lineTo(i * gridSize, canvas.height);
                ctx.stroke();
                
                ctx.beginPath();
                ctx.moveTo(0, i * gridSize);
                ctx.lineTo(canvas.width, i * gridSize);
                ctx.stroke();
            }
            
            // 绘制食物（草莓）
            ctx.fillStyle = '#2ecc71';
            ctx.beginPath();
            ctx.arc(foodX * gridSize + gridSize/2, foodY * gridSize + gridSize/2, gridSize/2 - 2, 0, Math.PI * 2);
            ctx.fill();
            
            // 添加草莓的细节
            ctx.fillStyle = '#e74c3c';
            ctx.beginPath();
            ctx.arc(foodX * gridSize + gridSize/2, foodY * gridSize + 6, 3, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制蛇身
            for (let i = 0; i < snake.length; i++) {
                // 蛇身颜色渐变
                let hue = (240 - i * 2) % 360;
                ctx.fillStyle = `hsl(${hue}, 80%, 50%)`;
                
                // 绘制蛇身
                ctx.fillRect(snake[i].x * gridSize, snake[i].y * gridSize, gridSize, gridSize);
                
                // 添加蛇身圆角
                ctx.fillStyle = `hsl(${hue}, 90%, 65%)`;
                ctx.beginPath();
                ctx.arc(
                    snake[i].x * gridSize + gridSize/2,
                    snake[i].y * gridSize + gridSize/2,
                    gridSize/2 - 1,
                    0,
                    Math.PI * 2
                );
                ctx.fill();
            }
            
            // 绘制蛇头
            if (snake.length > 0) {
                ctx.fillStyle = '#3498db';
                ctx.beginPath();
                ctx.arc(
                    snake[0].x * gridSize + gridSize/2,
                    snake[0].y * gridSize + gridSize/2,
                    gridSize/2 - 1,
                    0,
                    Math.PI * 2
                );
                ctx.fill();
                
                // 绘制蛇的眼睛
                ctx.fillStyle = '#fff';
                ctx.beginPath();
                ctx.arc(
                    snake[0].x * gridSize + gridSize/2 + (dx * 4),
                    snake[0].y * gridSize + gridSize/2 + (dy * 4),
                    3,
                    0,
                    Math.PI * 2
                );
                ctx.fill();
            }
        }
        
        // 移动蛇
        function moveSnake() {
            // 计算新的头部位置
            const headX = snake[0].x + dx;
            const headY = snake[0].y + dy;
            
            // 游戏结束检查：撞墙
            if (headX < 0 || headY < 0 || headX >= tileCount || headY >= tileCount) {
                endGame();
                return;
            }
            
            // 游戏结束检查：撞到自己
            for (let i = 0; i < snake.length; i++) {
                if (snake[i].x === headX && snake[i].y === headY) {
                    endGame();
                    return;
                }
            }
            
            // 添加新的头部
            snake.unshift({x: headX, y: headY});
            
            // 移除尾部（如果蛇没有吃到食物）
            if (snake.length > snakeLength) {
                snake.pop();
            }
            
            // 检查是否吃到食物
            if (headX === foodX && headY === foodY) {
                // 增加分数
                score += 10;
                scoreElement.textContent = score;
                
                // 增加蛇的长度
                snakeLength++;
                
                // 每吃5个食物提高速度
                if (score % 50 === 0) {
                    gameSpeed = Math.max(gameSpeed - 10, 60);
                    clearInterval(gameInterval);
                    gameInterval = setInterval(gameLoop, gameSpeed);
                }
                
                // 放置新食物
                placeFood();
            }
        }
        
        // 放置新食物
        function placeFood() {
            // 检查新食物位置是否与蛇身重叠
            let validPlacement = false;
            
            while (!validPlacement) {
                foodX = Math.floor(Math.random() * tileCount);
                foodY = Math.floor(Math.random() * tileCount);
                
                validPlacement = true;
                for (let i = 0; i < snake.length; i++) {
                    if (snake[i].x === foodX && snake[i].y === foodY) {
                        validPlacement = false;
                        break;
                    }
                }
            }
        }
        
        // 重置游戏
        function resetGame() {
            // 重置游戏状态
            snake = [];
            snakeLength = 3;
            score = 0;
            snakeX = 10;
            snakeY = 10;
            dx = 0;
            dy = 0;
            gameSpeed = 120;
            gameOver = false;
            
            // 重置蛇的初始位置
            for (let i = 0; i < snakeLength; i++) {
                snake.push({x: snakeX - i, y: snakeY});
            }
            
            // 重置分数显示
            scoreElement.textContent = score;
            
            // 放置食物
            placeFood();
            
            // 关闭游戏结束画面
            document.querySelector('.game-over').style.display = 'none';
        }
        
        // 游戏结束
        function endGame() {
            gameOver = true;
            isPaused = true;
            
            // 更新最高分
            if (score > highScore) {
                highScore = score;
                highScoreElement.textContent = highScore;
                localStorage.setItem('snakeHighScore', highScore);
            }
            
            // 显示游戏结束画面
            finalScoreElement.textContent = score;
            document.querySelector('.game-over').style.display = 'flex';
            
            clearInterval(gameInterval);
        }
        
        // 游戏主循环
        function gameLoop() {
            moveSnake();
            drawGame();
        }
        
        // 开始游戏
        function startGame() {
            if (gameOver) {
                resetGame();
            }
            
            if (!isPaused && gameInterval) return;
            
            isPaused = false;
            gameOver = false;
            
            // 确保蛇有初始方向
            if (dx === 0 && dy === 0) {
                dx = 1;
            }
            
            clearInterval(gameInterval);
            gameInterval = setInterval(gameLoop, gameSpeed);
        }
        
        // 暂停游戏
        function pauseGame() {
            if (gameOver || isPaused) return;
            
            isPaused = true;
            clearInterval(gameInterval);
        }
        
        // 按键控制
        function keyDownHandler(e) {
            if (isPaused && e.key === 'Enter') {
                startGame();
                return;
            }
            
            // 方向控制（不能直接反向移动）
            switch(e.key) {
                case 'ArrowUp':
                    if (dy === 0) {
                        dx = 0;
                        dy = -1;
                    }
                    break;
                case 'ArrowDown':
                    if (dy === 0) {
                        dx = 0;
                        dy = 1;
                    }
                    break;
                case 'ArrowLeft':
                    if (dx === 0) {
                        dx = -1;
                        dy = 0;
                    }
                    break;
                case 'ArrowRight':
                    if (dx === 0) {
                        dx = 1;
                        dy = 0;
                    }
                    break;
                case ' ':
                    if (isPaused) {
                        startGame();
                    } else {
                        pauseGame();
                    }
                    break;
            }
        }
        
        // 移动端控制
        function setupMobileControls() {
            document.querySelector('.mobile-controls .up').addEventListener('click', () => {
                if (dy === 0) {
                    dx = 0;
                    dy = -1;
                }
            });
            
            document.querySelector('.mobile-controls .down').addEventListener('click', () => {
                if (dy === 0) {
                    dx = 0;
                    dy = 1;
                }
            });
            
            document.querySelector('.mobile-controls .left').addEventListener('click', () => {
                if (dx === 0) {
                    dx = -1;
                    dy = 0;
                }
            });
            
            document.querySelector('.mobile-controls .right').addEventListener('click', () => {
                if (dx === 0) {
                    dx = 1;
                    dy = 0;
                }
            });
        }
        
        // 初始化游戏
        function initGame() {
            resetGame();
            
            // 设置事件监听器
            document.addEventListener('keydown', keyDownHandler);
            document.getElementById('start-btn').addEventListener('click', startGame);
            document.getElementById('pause-btn').addEventListener('click', pauseGame);
            document.getElementById('reset-btn').addEventListener('click', resetGame);
            document.getElementById('play-again-btn').addEventListener('click', resetGame);
            document.getElementById('play-again-btn').addEventListener('click', startGame);
            
            // 设置移动端控制
            setupMobileControls();
            
            // 初始绘制
            drawGame();
        }
        
        // 启动游戏
        window.onload = initGame;
    </script>
</body>
</html>